package com.example.testproject.adapter

import android.util.Log
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.example.testproject.R
import com.example.testproject.bean.RvAdvancedBean
import kotlinx.android.synthetic.main.item_parent_rv_advanced.view.*

/**
 *
 * @ClassName: RvAdvancedParentAdapter
 * @Author: android 超级兵
 * @CreateDate: 10/22/21$ 10:14 AM$
 * TODO
 */
class RvAdvancedParentAdapter(data: MutableList<RvAdvancedBean>?) :
    BaseQuickAdapter<RvAdvancedBean, BaseViewHolder>(R.layout.item_parent_rv_advanced, data) {
    override fun convert(helper: BaseViewHolder, item: RvAdvancedBean) {
        // 是否全选
        helper.itemView.parentCheckBox.isChecked = item.isParentSelect

        helper.itemView.parentCheckBox.text = item.ParentTitle

        // 创建 RecyclerView
        val adapter = buildChildRecyclerView(helper.itemView.parentRv, item.child)

        // 接口回调
        adapter.childCallBack = object : RvAdvancedChildAdapter.RvChildCallBack {
            override fun childCallBack(temp: Int) {
                // 畜种的个数为
                Log.i("szjTemp", "size:${adapter.data.size}\t $temp")

                item.isParentSelect = adapter.data.size == temp
                notifyDataSetChanged()

                // 子类回调
                parentCallBack.callBack()

            }
        }

        // checkBox 点击
        helper.itemView.parentCheckBox.setOnClickListener {
            val isChecked = helper.itemView.parentCheckBox.isChecked
            item.isParentSelect = isChecked

            adapter.data.forEach {
                // 如果当前有未选中的 这数量变为1
                if (!it.isChildSelect) {
                    it.number = 1
                }

                it.isChildSelect = item.isParentSelect
            }

            adapter.notifyDataSetChanged()

            // 父类回调
            parentCallBack.callBack()
        }
    }

    private fun buildChildRecyclerView(
        parentRv: RecyclerView,
        child: List<RvAdvancedBean.ChildBean>,
    ) = let {
        val rvAdvancedChildAdapter = RvAdvancedChildAdapter(child)
        parentRv.layoutManager = LinearLayoutManager(mContext)
        parentRv.adapter = rvAdvancedChildAdapter

        rvAdvancedChildAdapter
    }

    interface RvParentCallBack {
        fun callBack()
    }

    lateinit var parentCallBack: RvParentCallBack
}